package activity

import (
	"activity_srv/activityclient"
	"api/internal/svc"
	"api/internal/types"
	"context"
	"github.com/zeromicro/go-zero/core/logx"
	"net/http"
)

type AliPaySeckillOrderNotifyLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAliPaySeckillOrderNotifyLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AliPaySeckillOrderNotifyLogic {
	return &AliPaySeckillOrderNotifyLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AliPaySeckillOrderNotifyLogic) AliPaySeckillOrderNotify(w http.ResponseWriter, r *http.Request) (resp *types.AliPaySeckillOrderNotifyResponse, err error) {
	// 1. 解析表单（go-pay 已自动验签）
	if err = r.ParseForm(); err != nil {
		logx.Error("解析表单失败：", err)
		w.Write([]byte("fail"))
		return
	}

	ouTtradeNo := r.FormValue("out_trade_no")  //订单号
	tradeStatus := r.FormValue("trade_status") //支付状态

	if tradeStatus == "TRADE_SUCCESS" {
		// 支付成功，更新订单状态 rpc out_trade_no trade_status
		// todo: 更新订单状态
		l.svcCtx.ActivityRpc.UpdateSeckillOrderStatus(l.ctx, &activityclient.UpdateSeckillOrderStatusRequest{
			OrderSn:     ouTtradeNo,
			OrderStatus: 2,
		})
	} else if tradeStatus == "TRADE_CLOSED" {
		// 支付失败，更新订单状态
		// todo: 更新订单状态
		l.svcCtx.ActivityRpc.UpdateSeckillOrderStatus(l.ctx, &activityclient.UpdateSeckillOrderStatusRequest{
			OrderSn:     ouTtradeNo,
			OrderStatus: 3,
		})
	} else if tradeStatus == "TRADE_FINISHED" {
		// 支付失败，更新订单状态
		// todo: 更新订单状态
		l.svcCtx.ActivityRpc.UpdateSeckillOrderStatus(l.ctx, &activityclient.UpdateSeckillOrderStatusRequest{
			OrderSn:     ouTtradeNo,
			OrderStatus: 4,
		})
	} else if tradeStatus == "WAIT_BUYER_PAY" {
		return
	}
	w.Write([]byte("success"))
	return

}
